package demo;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.animation.Animation;
import javafx.util.Duration;                 // 持续时间
import javafx.animation.Timeline;			 // 设置循环次数,使用关键�?
import javafx.animation.KeyFrame;            // 关键�?

// 图片播放器
public class ImagePlayer extends Application { 
	private StackPane root = new StackPane();
	private Image image; 
	private ImageView iv;
	private Timeline timeline;		// 时间线动画(可以添加多个关键帧)
	private int count = 0;
	
	public static void main(String[] args) {
		Application.launch(args);
	}
	
	@Override
	public void start(Stage stage) {
		
		iv = new ImageView();
		root.getChildren().add(iv);
		
		Scene scene = new Scene(root, 700, 450);
		stage.setScene(scene);
		stage.show();
		
		// 动画
		timeline = new Timeline(new KeyFrame(Duration.seconds(2), e -> {
			String message = "image/" + count%4 + ".jpg";
			image = new Image(message);  
			iv.setImage(image); 
			iv.setFitWidth(700);
			iv.setFitHeight(450);    
			count++;
		}));
		timeline.setCycleCount(Timeline.INDEFINITE);
		timeline.play();
		
		// 监听
		// 获得在一个周期中的时间
		timeline.currentTimeProperty().addListener(e -> {
			System.out.println(String.format("%.2f", timeline.getCurrentTime().toSeconds()) );	
		});
		
		// 事件
		root.setOnMouseClicked(e -> controlStatus());
	}
	
	 // 控制动画的停放(四种状态)
	public void controlStatus() {
		if(timeline.getStatus() == Animation.Status.RUNNING) {
			timeline.stop();
		} else {
			timeline.play();
		}
	}
}
